package com.company.ems.util;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import com.company.ems.mapper.EmployeeMapper;
import com.company.ems.mapper.UserMapper;

public class MyBatisUtil {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {

            PooledDataSource dataSource = new PooledDataSource();
            dataSource.setDriver("com.mysql.cj.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/db05?useSSL=false&serverTimezone=UTC");
            dataSource.setUsername("root");
            dataSource.setPassword("123456");


            Environment env = new Environment(
                    "development",
                    new JdbcTransactionFactory(),
                    dataSource
            );


            Configuration config = new Configuration(env);
            config.addMapper(UserMapper.class);
            config.addMapper(EmployeeMapper.class);
            config.getTypeAliasRegistry().registerAlias("User", com.company.ems.model.User.class);
            config.getTypeAliasRegistry().registerAlias("Employee", com.company.ems.model.Employee.class);


            sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
            System.out.println("MyBatis纯Java配置初始化成功！");
        } catch (Exception e) {
            System.err.println("MyBatis初始化失败：" + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("MyBatis初始化失败", e);
        }
    }


    public static SqlSession getSqlSession() {
        if (sqlSessionFactory == null) {
            throw new RuntimeException("SqlSessionFactory未初始化");
        }
        return sqlSessionFactory.openSession(true);
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}